package com.itobase.statusDetect.Service.impl;

import com.itobase.statusDetect.Model.Course;
import com.itobase.statusDetect.Repository.CourseRepository;
import com.itobase.statusDetect.Service.CourseService;
import com.itobase.statusDetect.Util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author htyu
 * @date 2019/2/24
 */

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    CourseRepository courseRepository;




    @Override
    public List<Course> getList(String keyword) {
        List<Course> list = courseRepository.findAll();
        List<Course> result;
        if(StringUtils.isNotEmpty(keyword)){
            result = list.stream().filter(course ->
                            course.getName().contains(keyword)||
                            course.getDescription().contains(keyword)||
                            course.getType().contains(keyword))
                    .collect(Collectors.toList());
        }else {
            result = list;
        }
        return result;
    }

    @Override
    public Course create(Course course) {
        checkExist(course.getName());
        return courseRepository.save(course);
    }

    @Override
    public Course detial(String id) {
        return courseRepository.findById(id).get();
    }

    @Override
    public Course updateCourse(Course course) {
        String name = course.getName();
        checkExist(name);
        Course course_1 = courseRepository.findByName(name);
        course_1.setName(name);
        course_1.setDescription(course.getDescription());
        course_1.setType(course.getType());
        return courseRepository.save(course_1);
    }

    private void checkExist(String name) {
        Course course = courseRepository.findByName(name);
        if (course!=null)
            throw new InvalidParameterException("课程名重复,请勿重复添加");
    }
}
